/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package db;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Order;

/**
 *
 * @author Martin Mohr Pedersen
 */
public class OrderDAO extends ObjectDAO {

    @Override
    public boolean insert(Object object) {
        
        Order order = (Order) object;
        String sql = "INSERT INTO \"Order\"(order_no, customer_id, date, total, discount,"
                + "payment_date, payment_type, delivery_fee, cash_on_delivery_fee)"
                + "VALUES(?,?,?,?,?,?,?,?,?)";
        
        PreparedStatement pstmt = prepareStatement(sql);
        
        try {
            startTransaction();
            
            pstmt.setInt(1, order.getOrderNo());
            pstmt.setNull(2, java.sql.Types.NULL);
            pstmt.setTime(3, new java.sql.Time(order.getDate().getTime()));
            pstmt.setDouble(4, order.getTotal());
            pstmt.setDouble(5, order.getDiscount());
            pstmt.setTime(6, new java.sql.Time(order.getPaymentDate().getTime()));
            pstmt.setString(7, order.getPaymentType());
            pstmt.setDouble(8, order.getDeliveryFee());
            pstmt.setDouble(9, order.getCashOnDeliveryFee());
            pstmt.execute();
            
            // todo: create logic for inserting related data in same transaction
            
            
            commitTransaction();
        } catch(SQLException sqlex) {
            try {
                rollbackTransaction();
            } catch (SQLException ex) {
                Logger.getLogger(OrderDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        return false;
    }

    @Override
    public boolean update(Object object) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean delete(Object object) {
        Order order = (Order) object;
        String sql = "DELETE FROM \"Order\" WHERE order_no = ?";
        
        PreparedStatement pstmt = prepareStatement(sql);
        try {
            pstmt.setInt(1, order.getOrderNo());
            pstmt.execute();
            return true;
        } catch (SQLException ex) {
            Logger.getLogger(OrderDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return false;
    }

    @Override
    public Order[] findAll(String where, Object... params) {

        return null;
    }

    private Order[] unpackResultSet(ResultSet results) throws SQLException {
        ArrayList<Order> list = new ArrayList<Order>();

        while (results.next()) {
            Order order = new Order();
            order.setOrderNo(results.getInt("order_no"));
            order.setDate(results.getDate("date"));
            order.setTotal(results.getDouble("total"));
            order.setDiscount(results.getDouble("discount"));
            order.setPaymentDate(results.getDate("payment_date"));
            order.setPaymentType(results.getString("payment_type"));
            order.setDeliveryFee(results.getDouble("delivery_fee"));
            order.setCashOnDeliveryFee(results.getDouble("cash_on_delivery_fee"));
            
            list.add(order);
        }
        
        return list.toArray(new Order[list.size()]);
    }

    @Override
    public Order findOne(String where, Object... params) {

        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Order findByPK(Object pk) {
        String sql = "SELECT * FROM \"Order\" WHERE order_no = ?";
        PreparedStatement pstmt;
        
        try {
            pstmt = prepareStatement(sql);
            pstmt.setObject(1, pk);
            
            return fetchOne(pstmt);
        } catch (SQLException ex) {
            Logger.getLogger(OrderDAO.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }
    
    private Order fetchOne(PreparedStatement pstmt) {
        
        try {
            ResultSet results = pstmt.executeQuery();
            Order[] orders = unpackResultSet(results);
        
            pstmt.close();
            
            if(orders.length < 1) { // prevent out of bounds exception
                return null;
            }
            
            return orders[0];
        } catch (SQLException ex) {
            Logger.getLogger(OrderDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return null;
    }
    
}
